//
//  XWalletViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/22.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XWalletViewController.h"
#import "XWalletHeadView.h"
#import "XHomeRecommendedCell.h"
#import "XWalletContentTableCell.h"
#import "XSelectWalletListView.h"
#import "XWalletReadyViewController.h"
#import "HMScannerController.h"
#import "LoginViewController.h"
#import "TransferTypeViewController.h"
#import "XCollectionViewController.h"
#import "ImportTheWalletViewController.h"
#import "CreatWalletViewController.h"
#import "WalletTool.h"
#import "EOSService.h"
#import "HMScannerViewController.h"
#import "ResourcesDetailsViewController.h"
#import "MemoryTradingViewController.h"
#import "TransferViewController.h"
#import "FoundModel.h"
#import "TokenListViewController.h"
#import "TokenDetailViewController.h"
#import "XHPermissionsViewController.h"
@interface XWalletViewController ()
@property (nonatomic,strong) XWalletHeadView *walletHeadView;
@property (nonatomic,strong) FlatButton *walletBtn;
@property (nonatomic,strong) EOSService *eosService;
@property (nonatomic,strong) NSMutableArray *contracts;
@property (nonatomic,assign) BOOL isLoading;
@end

@implementation XWalletViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)loadMore:(BOOL)isMore{
    if (!isMore) {
        [self getaccountInfo];
    }
}
#pragma mark - httpEos
- (void)getaccountInfo{
    DLog(@"请求");
    if (!self.isLoading) {
        self.isLoading = YES;
    }else{
        [self.view makeToast:@"请勿频繁刷新"];
        return;
    }
    kWeakSelf(self);
    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            if (![self.eosService.accountResult.account_name isEqualToString:self.eosService.wallet.wallet_name]) {
                return;
            }
            if (self.eosService.permission.length) {
                [[XHDataBaseManager shareInstance]updateWalletToDB:self.eosService.wallet];
            }else{
                [XAlertTool alertTitle:@"提示" message:@"当前账号权限已经变更，前往查看账号权限是否正常？" cancelAction:^{
                    
                } sureAction:^{
                    XHPermissionsViewController *vc = [XHPermissionsViewController new];
                    vc.wallet = weakself.eosService.wallet;
                    [kCurrentVC.navigationController pushViewController:vc animated:YES];
                }];
            }
        }else{
            [weakself.view makeToast:errorMsg];
        }
        [weakself.eosService getMyTokenListComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
            weakself.isLoading = NO;
            if (success) {
                KDISPATCH_GLOBAL_QUEUE_DEFAULT(^{
                    weakself.contracts = [NSMutableArray arrayWithArray:weakself.eosService.wallet.contracts];
                    KDISPATCH_MAIN_THREAD(^{
                        weakself.walletHeadView.max_valuation = weakself.eosService.max_valuation;
                        [weakself.tableView reloadData];
                    });
                });
            }else{
                //[self.view makeToast:errorMsg];
            }
            [weakself reloadWallectData];
            [weakself endHeaderFooterRefreshing];
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.eosService.wallet = CURRENT_WALLET;
    [self config];
    [self reloadWallectData];
}

- (void)config{
    if (CURRENT_WALLET) {
        if (self.childViewControllers.count==1) {
            UIViewController*vc = [self.childViewControllers firstObject];
            [vc.view removeFromSuperview];
            [vc removeFromParentViewController];
        }
        if (!self.isLoading) {
            [self loadMore:NO];
        }
    }else if(self.childViewControllers.count==0){
        XWalletReadyViewController *ready = [XWalletReadyViewController new];
        ready.view.frame = self.view.bounds;
        [self.view addSubview:ready.view];
        [self addChildViewController:ready];
    }
}

- (void)reloadWallectData{
    [self.walletBtn setTitle:self.eosService.wallet.wallet_name forState:UIControlStateNormal];
    [self.walletBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:AdaptedWidth(5)];
}

#pragma mark - table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1+(self.eosService.myTokenList.count?1:0);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        XHomeRecommendedCell *cell = [XHomeRecommendedCell cellForTableView:tableView];
        cell.data = @[[FoundRecommendModel initName:XLocalized(@"转账") LogoImage:@"TRUN"],[FoundRecommendModel initName:XLocalized(@"收款") LogoImage:@"COLLECTION"],[FoundRecommendModel initName:XLocalized(@"资源详情") LogoImage:@"RESOURCE"],[FoundRecommendModel initName:XLocalized(@"RAM交易") LogoImage:@"RAM"]];
        kWeakSelf(self);
        cell.ClickIndexBlock = ^(NSInteger index) {
            if (index==0) {
                TransferTypeViewController *vc = [TransferTypeViewController new];
                [weakself.navigationController pushViewController:vc animated:YES];
            }else if (index==1){
                XCollectionViewController*vc = [XCollectionViewController new];
                [weakself.navigationController pushViewController:vc animated:YES];
            }else if (index==2){
                ResourcesDetailsViewController *vc = [ResourcesDetailsViewController new];
                vc.wallet = self.eosService.wallet;
                [weakself.navigationController pushViewController:vc animated:YES];
            }else if(index==3){
                MemoryTradingViewController*vc = [MemoryTradingViewController new];
                vc.wallet = self.eosService.wallet;
                [weakself.navigationController pushViewController:vc animated:YES];
            }
        };
        return cell;
    }else{
        XWalletContentTableCell *cell = [XWalletContentTableCell cellForTableView:tableView];
        kWeakSelf(self);
        cell.AddBlock = ^{
            TokenListViewController *vc = [TokenListViewController new];
            vc.wallet = weakself.eosService.wallet;
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        cell.eosData = self.eosService.myTokenList;
        cell.data = self.contracts;
        cell.DeleteBlock = ^(NSIndexPath * _Nonnull indexPath, TokenInfo * _Nonnull token) {
            if (indexPath.section == 0) {
                ///记录删除自己所有的资产的token
                NSMutableArray*codes = [NSMutableArray arrayWithArray:weakself.eosService.wallet.codes];
                ///删除自己添加的资产的合约
                if ([codes containsObject:token.code]) {
                    [codes removeObject:token.code];
                }
                weakself.eosService.wallet.codesJson = [codes modelToJSONString];
                NSMutableArray*deleteCodes = [NSMutableArray arrayWithArray:weakself.eosService.wallet.deleteCodes];
                if (![deleteCodes containsObject:token.code]) {
                    [deleteCodes addObject:token.code];
                }
                weakself.eosService.wallet.deleteCodesJson = [deleteCodes modelToJSONString];
                [[XHDataBaseManager shareInstance]updateWalletToDB:weakself.eosService.wallet];
                if ([weakself.eosService.myTokenList containsObject:token]) {
                    [weakself.eosService.myTokenList removeObject:token];
                }
                [weakself.tableView reloadData];
            }else{
                ///删除j自己添加的资产
                [self.contracts enumerateObjectsUsingBlock:^(TokenInfo * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj.code isEqualToString:token.code]) {
                        [self.contracts removeObject:obj];
                    }
                }];
                weakself.eosService.wallet.contractsJson = [self.contracts modelToJSONString];
                NSMutableArray*codes = [NSMutableArray arrayWithArray:weakself.eosService.wallet.codes];
                ///删除自己添加的资产的合约
                if ([codes containsObject:token.code]) {
                    [codes removeObject:token.code];
                }
                weakself.eosService.wallet.codesJson = [codes modelToJSONString];
                [[XHDataBaseManager shareInstance]updateWalletToDB:weakself.eosService.wallet];
                [weakself.tableView reloadData];
            }
        };
        
        cell.DidSeletBlock = ^(NSIndexPath * _Nonnull indexPath, TokenInfo * _Nonnull token) {          
            TokenDetailViewController *vc = [TokenDetailViewController new];
            vc.token = token;
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return kHomeRecommendedHeight;
    }
    return XWalletContentTableDefaultH+(self.eosService.myTokenList.count+self.contracts.count)*XWalletContentTableCellHeight;
}
#pragma mark - 事件
- (void)rightBtnClick:(UIButton*)rightBtn{
    if (rightBtn.tag == 1000) {
        [self scanGroup];
    }else{
        ImportTheWalletViewController *vc = [ImportTheWalletViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)scanGroup {
    kWeakSelf(self);
    HMScannerViewController *scanner = [[HMScannerViewController alloc] initWithCardName:nil avatar:nil completion:^(NSString *stringValue) {
        if ([RegularExp validateEosAccountName:stringValue]) {
            TransferViewController *vc = [TransferViewController new];
            vc.account = stringValue;
            [weakself.navigationController pushViewController:vc animated:YES];
        }else{
            [weakself.view makeToast:XLocalized(@"不是EOS账号")];
        }
    }];
    [self.navigationController pushViewController:scanner animated:YES];
}
#pragma mark- UI
- (void)setupUI{
     self.navigationItem.title = @"";
    [self addNavigationItemWithImageNames:@[@"black_qcode",@"black_wallet",] isLeft:NO target:self action:@selector(rightBtnClick:) tags:@[@1000,@1001]];
    self.tableView.tableHeaderView = self.walletHeadView;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.navigationItem.leftBarButtonItem = nil;
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, 44.0f)];
    self.navigationItem.titleView = titleView;
    
    self.walletBtn = [FlatButton button];
    self.walletBtn.frame = CGRectMake(AdaptedWidth(7), (44-AdaptedWidth(25))*.5, AdaptedWidth(143), AdaptedWidth(25));
    [titleView addSubview:self.walletBtn];
    self.walletBtn.layer.cornerRadius = AdaptedWidth(12.5);
    [self.walletBtn setBackgroundColor:UIColorHex(#F7F7F7)];
    self.walletBtn.titleLabel.font = kBoldFont(15);
    [self.walletBtn setTitleColor:kNavTintColor forState:UIControlStateNormal];
    [self.walletBtn setImage:IMAGE_NAMED(@"black_arrow") forState:UIControlStateNormal];
    [self.walletBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:AdaptedWidth(9)];
    kWeakSelf(self);
    [self.walletBtn addTapBlock:^(UIButton * _Nonnull btn) {
        [XSelectWalletListView showList:[[XHDataBaseManager shareInstance]selectAllLocalWallet] selectWallet:CURRENT_WALLET selectAction:^(Wallet * _Nonnull selectWallet) {
            if (!weakself.isLoading) {
                [WalletTool setCurrentWallet:selectWallet];
                weakself.eosService.wallet = selectWallet;
                [weakself loadMore:NO];
            }else{
                [weakself.view makeToast:@"请勿频繁切换钱包"];
            }
      
        } cancelAction:^{
            
        } importAction:^{
            ImportTheWalletViewController *vc = [ImportTheWalletViewController new];
            [weakself.navigationController pushViewController:vc animated:YES];
        }];
    }];
    self.tableView.mj_footer = nil;
    self.walletHeadView.PropertyBlock = ^{
        [weakself.tableView reloadData];
    };
}



#pragma mark - getter
- (XWalletHeadView*)walletHeadView{
    if (!_walletHeadView) {
        _walletHeadView = [[XWalletHeadView alloc] initWithFrame:CGRectMake(0, 0, 0, AdaptedWidth(110))];
    }
    return _walletHeadView;
}
- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
    }
    return _eosService;
}

@end
